﻿using System.Management;
using Microsoft.Win32;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;

namespace DataAcquisition
{
 
    internal class RegisterClass
    {
        private static string RegeditKey = "Software\\DataAcquisition\\RegistrationCode";

        private static string publicKey = "<RSAKeyValue><Modulus>r/zlNAAkABK7/ZiEhGKE35Bjnp18xPmdaVy8qtqslpufXkHh0QdWd5AcMJ5DNDpleRbM40VxJslf2Xs8wpl44dkw8JRXxzPGi5mlknKUQVs1TAPCyKCXVtSE/c8C74BMFX6XXJBiLTHQC1TYgaUaj7qMMKltL+9+x31uwu1bpZ0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        private string[] ContentList = { };

        public static int InitRegedit()
        {
            string registrationCode = RegisterClass.ReadSetting("", "Code", "-1");
            if (registrationCode == "-1")
            {
                
            }

            return 0;
        }

        public static string DecryptKey()
        {
            string key = string.Empty;
            string registrationCode = RegisterClass.ReadSetting("", "Code", "-1");
            if (registrationCode != "-1")
            {
                string[] list = registrationCode.Split("|");
                if (list.Length >= 2)
                {
                    try
                    {
                        string decryptData = RSAUntil.PublicKeyDecrypt(publicKey, list[1]);
                        key = new string(decryptData.ToCharArray().Reverse().ToArray());
                        //string content = DecryptDES(list[0], key);
                        //code = content;
                    }
                    catch (Exception)
                    {
                        key = "-999";
                        Log.Debug("权限码解析失败");
                    }
                }
            }
            return key;
        }

        public static string RegistrationCode()
        {
            string code = string.Empty;
            string registrationCode = RegisterClass.ReadSetting("", "Code", "-1");
            if (registrationCode != "-1")
            {
                string[] list = registrationCode.Split("|");
                if (list.Length >= 2)
                {
                    string key = DecryptKey();
                    if (key.Length > 0 && key != "-999")
                    {
                        string content = DecryptDES(list[0], key);
                        code = content;
                    }
                    else
                    {
                        code = "-999";
                    }
                }
            }
            return code;
        }

        public static string StartTime()
        {
            string content = RegistrationCode();
            string[] dataList = content.Split("-");
            if (dataList.Length >= 2)
            {
                return dataList[1];
            }
            else
            {
                return "";
            }
        }

        public static string EndTime()
        {
            string content = RegistrationCode();
            string[] dataList = content.Split("-");
            if (dataList.Length >= 3)
            {
                return dataList[2];
            }
            else
            {
                return "";
            }
        }

        public static string DecryptDES(string cipherText, string key)
        {
            byte[] iv = new byte[8];
            byte[] array = Convert.FromBase64String(cipherText);

            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = Encoding.ASCII.GetBytes(key);
                des.IV = iv;

                ICryptoTransform cryptoTransform = des.CreateDecryptor();

                using (MemoryStream memoryStream = new MemoryStream(array))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
                    {
                        using (StreamReader streamReader = new StreamReader(cryptoStream))
                        {
                            return streamReader.ReadToEnd();
                        }
                    }
                }
            }
        }

        /*CPUid*/
        public static string GetCpuId()
        {
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances();

            string strCpuID = null;
            foreach (ManagementObject mo in moc)
            {
                strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                break;
            }
            return strCpuID;
        }

        /*当前时间*/
        public static string GetNowDate()
        {
            string NowDate = DateTime.Now.ToString("yyyyMMdd"); //.Year + DateTime.Now.Month + DateTime.Now.Day).ToString();

            //     DateTime date = Convert.ToDateTime(NowDate, "yyyy/MM/dd");
            return NowDate;
        }

        /* 生成序列号 */
        public static string CreatSerialNumber()
        {
            string SerialNumber = GetCpuId() + "-" + "20110915";
            return SerialNumber;
        }

        /* 
         * i=1 得到 CUP 的id 
         * i=0 得到上次或者 开始时间 
         */
        public static string GetSoftEndDateAllCpuId(int i, string SerialNumber)
        {
            if (i == 1)
            {
                string cupId = SerialNumber.Substring(0, SerialNumber.LastIndexOf("-")); // .LastIndexOf("-"));

                return cupId;
            }
            if (i == 0)
            {
                string dateTime = SerialNumber.Substring(SerialNumber.LastIndexOf("-") + 1);
                //  dateTime = dateTime.Insert(4, "/").Insert(7, "/");
                //  DateTime date = Convert.ToDateTime(dateTime);

                return dateTime;
            }
            else
            {
                return string.Empty;
            }
        }

        /*写入注册表*/
        public static void WriteSetting(string Section, string Key, string Setting)
        {
            string text1 = Section;
            RegistryKey key1 = Registry.CurrentUser.CreateSubKey(RegeditKey);
            if (key1 == null)
            {
                return;
            }
            try
            {
                key1.SetValue(Key, Setting);
            }
            catch (Exception)
            {
                return;
            }
            finally
            {
                key1.Close();
            }

        }

        /*读取注册表*/
        public static string ReadSetting(string Section, string Key, string Default)
        {
            if (Default == null)
            {
                Default = "-1";
            }
            string text2 = Section;
            RegistryKey key1 = Registry.CurrentUser.OpenSubKey(RegeditKey);
            if (key1 != null)
            {
                object obj1 = key1.GetValue(Key, Default);
                key1.Close();
                string data = "-1";
                if (obj1 != null)
                {
                    if ((obj1 is string))
                    {
                        data = (string)obj1;
                    }
                }
                return data;
            }

            return Default;
        }
    }
}
